
using System;
using System.Data;
using System.Linq;
using System.Linq.Dynamic;
using System.Linq.Dynamic.Core;
using System.Linq.Expressions;
using System.Threading.Tasks;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;

using Abp.UI;
using Abp.AutoMapper;
using Abp.Extensions;
using Abp.Authorization;
using Abp.Domain.Repositories;
using Abp.Application.Services.Dto;
using Abp.Linq.Extensions;
 
using JYJ.AiYard.StationManagement.TbJLPayParams.Dtos;
using JYJ.AiYard.StationManagement.TbJLPayParams.DomainService;
using JYJ.AiYard.StationManagement.TbJLPayParams.Authorization;
using Microsoft.AspNetCore.Http;
using JYJ.AiYard.Database;
using JYJ.AiYard.StationManagement.YardCommonHald;
using JYJ.AiYard.StationManagement.YardReport;

namespace JYJ.AiYard.StationManagement.TbJLPayParams
{
    /// <summary>
    /// TbJLPayParams应用层服务的接口实现方法  
    ///</summary>
    [AbpAuthorize]
    public class TbJLPayParamsAppService : AiYardAppServiceBase, ITbJLPayParamsAppService
    {
        private readonly IRepository<TbJLPayParams, long> _entityRepository;

        private readonly ITbJLPayParamsManager _entityManager;

		private readonly IHttpService _httpService;

		protected IHttpContextAccessor _httpContext;

		/// <summary>
		/// 构造函数 
		///</summary>
		public TbJLPayParamsAppService(
        IRepository<TbJLPayParams, long> entityRepository
        ,ITbJLPayParamsManager entityManager
		, IHttpService httpService
		, IHttpContextAccessor httpContextAccessor
		)
        {
            _entityRepository = entityRepository; 
            _entityManager=entityManager;
			_httpService = httpService;
			_httpContext = httpContextAccessor;
		}


        /// <summary>
        /// 获取TbJLPayParams的分页列表信息
        ///</summary>
        /// <param name="input"></param>
        /// <returns></returns>
		[AbpAuthorize(TbJLPayParamsPermissions.Query)] 
        public async Task<PagedResultDto<TbJLPayParamsListDto>> GetPaged(GetTbJLPayParamssInput input)
		{
			List<long> StationList = new List<long>();
			tbQFilterText filterText = input.FilterText.ToObject<tbQFilterText>();
			if (filterText.StationId == null || filterText.StationId <= 0)
			{
				StationList = GetCurrenUserOrganizationAndChildrenUnit();
			}
			else
			{
				StationList.Add((long)filterText.StationId);
			}
			var query = _entityRepository.GetAll().Where(o => StationList.Contains(o.Station_ID));
			// TODO:根据传入的参数添加过滤条件
            

			var count = await query.CountAsync();

			var entityList = await query               
                    .OrderBy(input.Sorting).AsNoTracking()
					.PageBy(input)
					.ToListAsync();

			//var entityListDtos = ObjectMapper.Map<List<TbJLPayParamsListDto>>(entityList);
			var entityListDtos =entityList.MapTo<List<TbJLPayParamsListDto>>();

			return new PagedResultDto<TbJLPayParamsListDto>(count,entityListDtos);
		}


		/// <summary>
		/// 通过指定id获取TbJLPayParamsListDto信息
		/// </summary>
		[AbpAuthorize(TbJLPayParamsPermissions.Query)] 
		public async Task<TbJLPayParamsListDto> GetById(EntityDto<long> input)
		{
			var entity = await _entityRepository.GetAsync(input.Id);

		    return entity.MapTo<TbJLPayParamsListDto>();
		}

		/// <summary>
		/// 获取编辑 TbJLPayParams
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		[AbpAuthorize(TbJLPayParamsPermissions.Create,TbJLPayParamsPermissions.Edit)]
		public async Task<GetTbJLPayParamsForEditOutput> GetForEdit(NullableIdDto<long> input)
		{
			var output = new GetTbJLPayParamsForEditOutput();
            TbJLPayParamsEditDto editDto;

			if (input.Id.HasValue)
			{
				var entity = await _entityRepository.GetAsync(input.Id.Value);

				editDto = entity.MapTo<TbJLPayParamsEditDto>();
			}
			else
			{
				editDto = new TbJLPayParamsEditDto();
			}

			output.TbJLPayParams = editDto;
			return output;
		}


		/// <summary>
		/// 添加或者修改TbJLPayParams的公共方法
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		[AbpAuthorize(TbJLPayParamsPermissions.Create,TbJLPayParamsPermissions.Edit)]
		public async Task CreateOrUpdate(CreateOrUpdateTbJLPayParamsInput input)
		{
            if (input.TbJLPayParams.Station_ID <= 0)
            {
                throw new UserFriendlyException("请选择确定的场所名称");
            }
            if (input.TbJLPayParams.Id.HasValue)
			{
				await Update(input.TbJLPayParams);
			}
			else
			{
				await Create(input.TbJLPayParams);
			}
		}


		/// <summary>
		/// 新增TbJLPayParams
		/// </summary>
		[AbpAuthorize(TbJLPayParamsPermissions.Create)]
		protected virtual async Task<TbJLPayParamsEditDto> Create(TbJLPayParamsEditDto input)
		{
            if (string.IsNullOrEmpty(input.Client_ID.ToString()))
                input.Client_ID = 0;

             
            //判断相同的客户端是否只存在一个
            var query = _entityRepository.GetAll()
                .Where(o => o.Client_ID == input.Client_ID && o.Station_ID == input.Station_ID && o.JL_mch_type==input.JL_mch_type);
            if (query.Count() > 0)
            {
                throw new UserFriendlyException("存在相同活动的客户端支付参数设置");
            }

            // var entity = ObjectMapper.Map <TbJLPayParams>(input);
            var entity=input.MapTo<TbJLPayParams>();
			

			entity = await _entityRepository.InsertAsync(entity);

			//JLQrDevice jLQr = GetJLQrDevice(entity.Station_ID, 1);


			return entity.MapTo<TbJLPayParamsEditDto>();
		}

		/// <summary>
		/// 编辑TbJLPayParams
		/// </summary>
		[AbpAuthorize(TbJLPayParamsPermissions.Edit)]
		protected virtual async Task Update(TbJLPayParamsEditDto input)
		{
            if (string.IsNullOrEmpty(input.Client_ID.ToString()))
                input.Client_ID = 0;

             
            //判断相同的客户端是否只存在一个
            var query = _entityRepository.GetAll()
                .Where(o => o.Client_ID == input.Client_ID && o.Station_ID == input.Station_ID && o.JL_mch_type == input.JL_mch_type && o.Id!=input.Id);
            if (query.Count() > 0)
            {
                throw new UserFriendlyException("存在相同活动的客户端支付参数设置");
            }

            var entity = await _entityRepository.GetAsync(input.Id.Value);
			input.MapTo(entity);

			// ObjectMapper.Map(input, entity);
		    await _entityRepository.UpdateAsync(entity);
		}



		/// <summary>
		/// 删除TbJLPayParams信息的方法
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		[AbpAuthorize(TbJLPayParamsPermissions.Delete)]
		public async Task Delete(EntityDto<long> input)
		{
			//TODO:删除前的逻辑判断，是否允许删除
			await _entityRepository.DeleteAsync(input.Id);
		}



		/// <summary>
		/// 批量删除TbJLPayParams的方法
		/// </summary>
		[AbpAuthorize(TbJLPayParamsPermissions.BatchDelete)]
		public async Task BatchDelete(List<long> input)
		{
			// TODO:批量删除前的逻辑判断，是否允许删除
			await _entityRepository.DeleteAsync(s => input.Contains(s.Id));
		}

		public JLQrDevice GetJLQrDevice(long Station_ID,int isTest)
		{
			JLQrDevice jLQr2 = new JLQrDevice();
			jLQr2.ret_code = "-1";
			jLQr2.ret_msg = "调用接口错误";
			jLQr2.term_no = "Normal";
			jLQr2.merch_no = "Normal";
			jLQr2.protocol_id = "Normal";
			jLQr2.device_no = "Normal";
			try
			{
				string host = _httpContext.HttpContext.Request.Host.Host.Replace("www", "pay").Replace("aiweb", "pay").Replace("webx", "pay").Replace("web.", "minipay.").Replace("yun4.", "pay.").Replace("p.", "t.");
#if DEBUG
				host = "localhost"; 
#endif 
				string Url = (host.Contains("minipay.") ? "https://" : "http://") + host + ":1888/api/v1.0/BarCodePay/GetJLQrDevice?StationId=" + Station_ID + "&isTest=" + isTest;

				string jLQr = _httpService.Get(Url).Trim();
				if (jLQr == "")
				{ 
					return jLQr2;
				}
				JLQrDevice jLQr1 = Json.ToObject<JLQrDevice>(jLQr);
				if (jLQr1.ret_code != "00")
				{
					jLQr2.ret_msg = jLQr1.ret_msg;
					jLQr2.ret_code = jLQr1.ret_code;
					 
					return jLQr2;
				}
				else
				{
					return jLQr1;
				}
			}
			catch (Exception ex)
			{
				return jLQr2;
			}
		}
 
		///// <summary>
		///// 导出TbJLPayParams为excel表,等待开发。
		///// </summary>
		///// <returns></returns>
		//public async Task<FileDto> GetToExcel()
		//{
		//	var users = await UserManager.Users.ToListAsync();
		//	var userListDtos = ObjectMapper.Map<List<UserListDto>>(users);
		//	await FillRoleNames(userListDtos);
		//	return _userListExcelExporter.ExportToFile(userListDtos);
		//}

	}
	public class JLQrDevice
	{
		public string ret_code { get; set; }
		public string ret_msg { get; set; }
		public string protocol_id { get; set; }
		public string merch_no { get; set; }
		public string term_no { get; set; }
		public string device_no { get; set; }

	}
}


